<template>
  <div class="outer-wrapper">
    <div id="stack-bar" ref="EchartOneRef">
    </div>

    <el-dialog width="60%" top="20vh" custom-class="custom-class" append-to-body v-model="dialogVisible"
      :title="mainTitle">
      <div class="dialog-inner" v-loading="loading" element-loading-background="rgba(18, 25, 58, 0.8)">
        <div id="forecast-and-pass" ref="EchartTwoRef"></div>
        <div id="forecast-and-pass" ref="EchartThreeRef"></div>
      </div>
    </el-dialog>

  </div>
</template>
<script>
window.EchartInsOne = null;
let EchartInsTwo = null;
let EchartInsThree = null;
import { max as lodashMax, min as lodashMin } from 'lodash'
import UndergroundData from '../files/ground831_R_new.json'
import PositionArr from '../files/positions831_P_Modify.json'
import Api from "@/api"
export default {
  /**
   * 水位站组件
  */
  /**
   *  "id": id,
      "cjsj": "创建时间",
      "gxsj": "更新时间",
      "sjly": "数据来源",
      "scbj": 删除标记,
      "swz_id": "id 站点名称",
      "clsj": "测量时间",
      "rq": "日期",
      "swbf": 1.14,
      "clsw": 测量水位,
      "scsw": 输出水位,
      "scsw56": 输出水位56,
      "scswws": 输出水位吴淞,
      "scswsd": 输出水位深度
  */
  name: "WaterLevelBase",
  props: {
    // 单位
    unit: {
      type: String,
      default: "单位: (%)"
    },
    // 数据
    resultData: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      series: [],
      yAxis: [],
      // 当前选择的站点
      currentSelectName: "",
      dialogVisible: false,
      loading: true,
    };
  },
  watch: {
    // 监听到数据变化，重新渲染
    resultData: {
      handler() {
        this.initOptionOne();
      },
      deep: true
    },
    dialogVisible(v) {
      if (!v) {
        if (EchartInsTwo) {
          EchartInsTwo.clear();
        }
      }
    }
  },
  computed: {
    mainTitle() {
      return `${this.currentSelectName}- 过去7天及未来7天水位值变化`
    }
  },
  unmounted() {
    if (window.EchartInsOne) {
      window.EchartInsOne.dispose();
    }
    if (EchartInsTwo) {
      EchartInsTwo.dispose();
    }
  },
  mounted() {
    this.initOptionOne();
  },
  methods: {
    // 初始化配置
    initOptionOne() {
      const that = this;
      if (!this.resultData.length) { return }
      const chartDom = this.$refs.EchartOneRef;
      window.EchartInsOne = echarts.init(chartDom);
      // 基准面
      echarts.registerMap("JZM", { geoJSON: UndergroundData });
      this.series = [];
      this.yAxis = this.resultData.map(o => {
        return [{ coord: [o.lc, o.yValue] }, { coord: [o.lc, o.yValue / 2] }];
      });
      const option = {
        title: {
          show: true,
          text: this.resultData[1].clsj ? this.resultData[1].clsj.split(" ")[0] : "",
          top: 2,
          left: 100,
          borderWidth: 1,
          borderColor: "rgba(255,255,255,0.5)",
          borderRadius: 2,
          padding: [5, 10],
          textStyle: {
            color: "#fff",
            fontWeight: 500,
            fontSize: 14
          }
        },
        color: ["#964B00", "#5EE0C5"],
        tooltip: {
          trigger: "item"
        },
        toolbox: {
          show: !1,
          orient: "vertical",
          left: "right",
          top: "center",
          feature: { dataView: { readOnly: !1 }, restore: {}, saveAsImage: {} }
        },
        visualMap: {
          show: false, min: 0, max: 3, text: ["High", "Low"], realtime: !1, calculable: !0,
          inRange: { color: ["#94e9fd", "#566684", "#858585"], colorAlpha: 0.7 },
        },
        yAxis: [{ type: "value", show: false }],
        xAxis: { axisLine: { show: !1 }, splitLine: { show: !1 } },
        // 文本 60% 需与 series 内的 60% 一致
        geo: {
          top: "60%",
          left: that.$parent.cj_qd + "px",
          right: that.$parent.cj_qd + "px",
          roam: !1,
          aspectScale: 1.2,
          silent: !0,
          zoom: 1.06,
          map: "JZM", itemStyle: { areaColor: "rgba(255,255,255,0)", borderColor: "rgba(255,255,255,0)" },
        },
        grid: {
          left: "0%",
          top: "0%",
          right: "0%",
          bottom: "0%",
          containLabel: false
        },
        legend: {
          show: false,
          right: 0,
          textStyle: {
            color: "#fff"
          }
        },
        series: [
          {
            name: "地面",
            type: "map",
            map: "JZM",
            zlevel: 10,
            roam: !1,
            left: that.$parent.cj_qd + "px",
            right: that.$parent.cj_qd + "px",
            top: "60%",
            bottom: "0%",
            aspectScale: 1.2,
            silent: !0,
            zoom: 1.06,
            label: {
              show: !0,
              color: "#fff",
              offset: [0, -30]
            },
            // 地面对应的点
            itemStyle: { color: "#ffffff", borderWidth: 0 },
            emphasis: {
              itemStyle: { color: "#00d5d5", shadowBlur: 8, shadowColor: "#c8fdfd" },
              label: { color: "#c8fdfd" }
            },
            data: [
              { name: "水面", value: 0, label: { show: false } },
              { name: "地面", value: 1, label: { show: false } },
              {
                name: "向家坝", value: 2, label: {
                  fontWeight: 600,
                  show: 1,
                  fontSize: 15,
                  formatter: ({ name: t }) => {
                    let o = that.resultData.find((t => t.name == "向家坝出库"));
                    return `${t} ${o?.scswsd == undefined ? 0 : o?.scswsd}  m³/s`
                  },
                  lineHeight: 10,
                  rotate: 45,
                  color: "#ff9800",
                  verticalAlign: "middle",
                  position: "insideTop",
                  distance: -40,
                  align: "center",
                  overflow: "breakAll",
                  offset: [0, 2]
                },
              },
              {
                name: "葛洲坝", value: 2, label: {
                  fontWeight: 600,
                  show: 1,
                  formatter: ({ name: t }) => {
                    let o = that.resultData.find((t => t.name == "葛洲坝出库"));
                    return `${t} ${o?.scswsd == undefined ? 0 : o?.scswsd}  m³/s`
                  },
                  lineHeight: 10,
                  rotate: 45,
                  fontSize: 15,
                  color: "#ff9800",
                  verticalAlign: "middle",
                  position: "insideTop",
                  distance: -30,
                  align: "center",
                  overflow: "breakAll",
                  offset: [50, 0]
                },
              },
              {
                name: "三峡",
                value: 2,
                label: {
                  fontWeight: 600,
                  show: 1,
                  distance: -30,
                  formatter: ({ name: t }) => {
                    let o = that.resultData.find((t => t.name == "三峡出库"));
                    return `${t} ${o?.scswsd == undefined ? 0 : o?.scswsd}  m³/s`
                  },
                  lineHeight: 10,
                  rotate: 45,
                  fontSize: 15,
                  color: "#ff9800",
                  verticalAlign: "middle",
                  position: "insideTop",
                  align: "center",
                  overflow: "breakAll",
                  offset: [30, 0]
                },
              }],
            nameMap: {}
          },
          {
            type: "scatter",
            name: "label",
            coordinateSystem: "geo",
            silent: !1,
            symbolSize: 4,
            tooltip: { show: !1 },
            zlevel: 999,
            animationDuration: 0,
            selectedMode: "multiple",
            select: {
              itemStyle: { color: "#fff840" },
              label: { color: "#fff840" }
            },
            emphasis: {
              itemStyle: {
                // 高亮时点的颜色。
                color: '#fadb14',
                areaColor: '#fadb14',
              },
              label: {
                color: '#fadb14'
              }
            },
            data: PositionArr.map((e => (e.geometry.coordinates.push(10), {
              name: e.properties.name,
              value: e.geometry.coordinates,
              label: {
                show: true,
                formatter: ({ name: t }) => {
                  let o = that.resultData.find((t => t.swz_id == e.properties.swz_id));
                  if (o == undefined) {
                    o = that.resultData.find((t => t.id == e.properties.swz_id));
                  }
                  return (t.split("（")[0]?.replace("）", "") || t.split("（")[0]) + "  " + (o?.scswsd || 0) + (o?.scswsd > 1000 ? 'm³/s' : 'm')
                },
                rotate: 45,
                color: "#ffffff",
                align: "left",
                distance: 0,
                verticalAlign: "middle",
                position: "insideTop",
                fontWeight: 400,
                fontSize: 14,
                // lineHeight: 10,
                offset: e.properties.offset || [5, 2],
                overflow: "breakAll"
              },
              data: e,
              itemStyle: { color: "#ffffff", borderWidth: 0 }
            })))
          }
        ]
      };
      option && window.EchartInsOne.setOption(option, true);




      // 点击事件
      window.EchartInsOne.on("click", function (e) {
        if (that.currentSelectName) {
          that.setSelect(that.currentSelectName, 'unselect');
        }
        that.currentSelectName = e.name;
        that.dialogVisible = true;
        that.searchWaterOf7daysData(e);
      })
    },
    // 选中与否
    setSelect(e, t = "highlight") {
      window.EchartInsOne.dispatchAction({ type: t, name: e })
    },
    // 获取 7 天水位数据 - 7 天过去 + 7 天未来
    async searchWaterOf7daysData(e) {
      this.loading = true;
      {
        // 7 天过去
        const resPass = await Api.get7WaterPassAnalysisListWhole({
          cfgName: "水位动态监测数据",
          map: {
            swz_id: e.data.data.properties.swz_id,
            time_b: dayjs().add(-7, 'day').format('YYYY-MM-DD') + ' 00:00:00',
            time_e: dayjs().add(7, 'day').format('YYYY-MM-DD HH:mm:ss')
          }
        });
        const passData = resPass.data.data;
        // 测量水位 过去值
        let clswData = passData.map(v => {
          return v.clsw
        })
        let timeData = passData.map(v => {
          return v.clsj
        })
        const maxData = parseInt(lodashMax(clswData)) + 2;
        const minData = parseInt(lodashMin(clswData)) - 2;
        const axisLabelInterval = parseInt(timeData.length / 10);
        this.loading = false;

        this.initOptionTwo({
          timeData,
          clswData,
          minData,
          maxData,
          axisLabelInterval
        });
      }

      {
        //未来7天
        Api.get7WaterForecastAnalysisListWhole().then(res => {
          if (res.content) {
            const forecastSiteData = e.data.data;
            this.doFilterData(forecastSiteData, res.content);
          }
        })
      }
    },
    doFilterData(selectedData, content) {
      if (!content || !content.length) { return }
      if (!selectedData.properties) { return }
      const forecastSiteName = selectedData.properties.forecastSiteName;
      const selectedArr = content.filter(v => {
        return v.forecastSiteName === forecastSiteName
      });

      // 预测水位的数据
      const forecastLevel = selectedArr.map(v => {
        return v.forecastLevel
      });
      // 预测的时间段
      const timeData = selectedArr.map(v => {
        return v.forecastWaterTime
      })
      const maxData = parseInt(lodashMax(forecastLevel)) + 2;
      const minData = parseInt(lodashMin(forecastLevel)) - 2;
      const axisLabelInterval = parseInt(timeData.length / 10);
      this.initOptionThree({
        timeData,
        forecastLevel,
        minData,
        maxData,
        axisLabelInterval
      });
    },
    // 初始化配置 
    initOptionTwo({ timeData, clswData, maxData, minData, axisLabelInterval }) {
      const chartDom = this.$refs.EchartTwoRef;
      EchartInsTwo = echarts.init(chartDom);
      const option = {
        backgroundColor: 'rgba(18, 25, 58, 0.8)',
        color: ['#f0c725'],
        title: {
          show: false,
          left: 'center',
          text: '水位变化',
          textStyle: {
            color: '#FFFFFF',
            fontSize: '14',
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: ['过去7天水位'],
          x: 'center',
          top: '25',
          textStyle: {
            color: '#c1cadf',
            "fontSize": 10
          },
          show: true
        },
        grid: {
          left: '6%',
          right: '4%',
          top: '25%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          show: true,
          orient: 'vertical',
          x: 'right',
          y: 'center'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: timeData,
          axisLine: {
            lineStyle: {
              color: 'rgba(240,199,37,0.5)'
            }
          },
          // interval 每一段有多少个 
          axisLabel: {
            interval: axisLabelInterval || 20,
            rotate: 0,
            color: '#c1cadf',
            formatter: function (v) {
              let tArr = dayjs(v).format('MM-DD HH');
              let head = tArr.split(" ")[0];
              let tail = tArr.split(" ")[1];
              return `${head}\n${tail} 时`
            }
          }
        },
        yAxis: {
          type: 'value',
          name: 'M',
          min: minData,
          max: maxData,
          nameTextStyle: {
            color: '#c1cadf',
            align: 'right',
            lineHeight: 10
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(240,199,37,0.5)'
            }
          },
          axisLabel: {
            interval: 0,
            color: '#c1cadf'
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: ['#aaa', '#ddd'],
              width: 0.5,
              type: 'dashed'
            }
          }
        },
        series: {
          name: '过去7天水位',
          type: 'line',
          smooth: true,
          symbolSize: 0,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: 'rgba(240,199,37,0.5)'
            }, {
              offset: 1,
              color: 'rgba(240,199,37,0.01)'
            }])
          },
          data: clswData,
          barWidth: '30%',
          itemStyle: { normal: { color: '#f0c725' } }
        }
      }
      option && EchartInsTwo.setOption(option, true);
    },
    // 初始化配置 
    initOptionThree({ timeData, forecastLevel, maxData, minData, axisLabelInterval }) {
      const chartDom = this.$refs.EchartThreeRef;
      EchartInsThree = echarts.init(chartDom);
      const option = {
        backgroundColor: 'rgba(18, 25, 58, 0.8)',
        color: ['#2196f3'],
        title: {
          show: false,
          left: 'center',
          text: '水位变化',
          textStyle: {
            color: '#FFFFFF',
            fontSize: '14',
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: ['未来7天水位'],
          x: 'center',
          top: '25',
          textStyle: {
            color: '#c1cadf',
            "fontSize": 10
          },
          show: true
        },
        grid: {
          left: '6%',
          right: '4%',
          top: '25%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          show: true,
          orient: 'vertical',
          x: 'right',
          y: 'center'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: timeData,
          axisLine: {
            lineStyle: {
              color: 'rgba(240,199,37,0.5)'
            }
          },
          // interval 每一段有多少个 
          axisLabel: {
            interval: axisLabelInterval || 20,
            rotate: 0,
            color: '#c1cadf',
            formatter: function (v) {
              let tArr = dayjs(v).format('MM-DD HH');
              let head = tArr.split(" ")[0];
              let tail = tArr.split(" ")[1];
              return `${head}\n${tail} 时`
            }
          }
        },
        yAxis: {
          type: 'value',
          name: 'M',
          min: minData,
          max: maxData,
          nameTextStyle: {
            color: '#c1cadf',
            align: 'right',
            lineHeight: 10
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(240,199,37,0.5)'
            }
          },
          axisLabel: {
            interval: 0,
            color: '#c1cadf'
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: ['#aaa', '#ddd'],
              width: 0.5,
              type: 'dashed'
            }
          }
        },
        series: {
          name: '未来7天水位',
          type: 'line',
          smooth: true,
          symbolSize: 0,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: 'rgba(30, 150, 240, 0.5)'
            }, {
              offset: 1,
              color: 'rgba(30, 150, 240, 0.01)'
            }])
          },
          data: forecastLevel,
          barWidth: '30%',
          itemStyle: { normal: { color: '#2196f3' } }
        }
      }
      option && EchartInsThree.setOption(option, true);
    }
  }
};
</script>

<style>
/* '' */
.custom-class.el-dialog {
  background-color: transparent;
  box-shadow: initial;
}

.custom-class .el-dialog__title {
  font-family: 'YouSheBiaoTiHei', Arial, Helvetica, sans-serif;
}

.custom-class .el-dialog__header {
  background-image: url(@/assets/images/image-popper-header.png);
  background-repeat: no-repeat;
  padding: 10px;
  padding-left: 30px;
}

.custom-class .el-dialog__body {
  padding: 0px;
  padding-top: 0;
}

.custom-class .el-dialog__headerbtn {
  width: 30px;
  height: 30px;
  top: 5px;
}

.custom-class .el-dialog__headerbtn .el-dialog__close {
  font-size: xx-large;
}

.self-folder-icon.el-icon {
  color: #ff9800;
}

.self-file-icon.el-icon {
  color: #607d8b;
}

/* tree 组件多行显示 */
.self-tree .el-tree-node {
  white-space: normal;
}

.self-tree .el-tree-node .el-tree-node__content {
  height: 100%;
}

/* 滑动条 */
.el-slider.slider-for-opacity {
  width: 60px;
}
</style>

<style lang="less" scoped>
#stack-bar {
  height: 100%;
}

#forecast-and-pass {
  height: 50%;
}

.dialog-inner {
  height: 500px;
}
</style>
